package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.DeviceType;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.Key;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.KeyManager;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class DIYAirRemoteActivity1 extends BaseActivity {
	private LinearLayout mBackL;
	private TextView mStatusBar;
	private TextView mTitleTv;
	private TextView mUserTv;
	private TextView mModeTv;
	private TextView mTypeTv;
	private EditText mNameed;
	private Button mEnsureB;
	private int type;
	private SVProgressHUD mSVProgressHUD;
	private List<Key> keys = new ArrayList<Key>();

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.nextstep1:
			// 点击完成
			// 校验型号 如不合格 则提示
			// 如合格 从KeyManager获取按键 上传遥控器 遥控器上传成功则上传按键
			// 上传成功则跳转回主界面
			String name = mNameed.getText().toString();
			if (DeviceManager.getInstance().checkName(name)) {
				ToastShow.Show(getApplicationContext(), "该名称已被使用，请重新命名！");
				return;
			}
			if (name.equals("")) {
				ToastShow.Show(getApplicationContext(), "设备名称不能为空，请重新命名！");
				return;
			}
			if (name.length() < 2) {
				ToastShow.Show(getApplicationContext(), "该名称长度过短，请重新命名！");
				return;
			}
			keys = KeyManager.getInstance().getDIYKeyList();
			save(name);
			break;

		default:
			break;
		}
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_diy2;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mTitleTv = $(R.id.title_tv);
		mTitleTv.setText("保存您的遥控器");
		mUserTv = $(R.id.name_tv);
		mModeTv = $(R.id.mode_tv);
		mTypeTv = $(R.id.type_tv);
		mNameed = $(R.id.name_ed);
		mEnsureB = $(R.id.nextstep1);
		type = getIntent().getIntExtra("type", 999);
		boolVersion();
		mBackL.setOnClickListener(this);
		mEnsureB.setOnClickListener(this);
		initData();
	}

	private void initData() {
		// TODO Auto-generated method stub
		String name = (String) SPUtils.get(getApplicationContext(), "user_name", "");
		mUserTv.setText(name);
		switch (type) {
		case DeviceType.DEVICE_TYPE_AIR_CONTROLLER:
			mTypeTv.setText(getString(R.string.yaokong_add_kongtiao));
			mModeTv.setText(mTypeTv.getText() + getString(R.string.remote_mode1));
			mNameed.setHint(getString(R.string.nameed1));
			break;
		case DeviceType.DEVICE_TYPE_BOX:
			mTypeTv.setText(getString(R.string.yaokong_add_hezi));
			mModeTv.setText(mTypeTv.getText() + getString(R.string.remote_mode1));
			mNameed.setHint(getString(R.string.nameed2));
			break;
		case DeviceType.DEVICE_TYPE_DVD:
			mTypeTv.setText(getString(R.string.yaokong_add_dvd));
			mModeTv.setText(mTypeTv.getText() + getString(R.string.remote_mode1));
			mNameed.setHint(getString(R.string.nameed3));
			break;
		case DeviceType.DEVICE_TYPE_FAN:
			mTypeTv.setText(getString(R.string.yaokong_add_fenshan));
			mModeTv.setText(mTypeTv.getText() + getString(R.string.remote_mode1));
			mNameed.setHint(getString(R.string.nameed4));
			break;
		case DeviceType.DEVICE_TYPE_PROJECTOR:
			mTypeTv.setText(getString(R.string.yaokong_add_touyingyi));
			mModeTv.setText(mTypeTv.getText() + getString(R.string.remote_mode1));
			mNameed.setHint(getString(R.string.nameed5));
			break;
		case DeviceType.DEVICE_TYPE_TV:
			mTypeTv.setText(getString(R.string.yaokong_add_tv));
			mModeTv.setText(mTypeTv.getText() + getString(R.string.remote_mode1));
			mNameed.setHint(getString(R.string.nameed6));
			break;

		default:
			break;
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	// 保存该遥控器
	private void save(String name) {
		mSVProgressHUD = new SVProgressHUD(DIYAirRemoteActivity1.this);
		mSVProgressHUD.showWithStatus("正在提交");
		// 上传设备
		RequestParams params = new RequestParams(HttpURL.UPLOAD_DEVICE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {

			obj.put("classification", "4");
			obj.put("key", "10000");
			obj.put("deviceModel", name);
			// obj.put("deviceModel", model);
			obj.put("deviceName", name);
			// obj.put("deviceName", model);
			if (type == DeviceType.DEVICE_TYPE_BOX) {
				type = DeviceType.DEVICE_TYPE_BOX2;
			} else {
				obj.put("deviceType", type + "");
			}
			obj.put("deviceVersion", "3.1.0");
			obj.put("deviceWifiSSID", name);
			obj.put("deviceId", "0");
			obj.put("productId", "4");
			obj.put("mainDeviceId", DeviceManager.getInstance().getmWlanId());
			obj.put("hid", DeviceManager.getInstance().hid);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.d("test", " upload obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("test", "upload=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String value = jsonObject.getString("resultCode");
					if (value.equals("1")) {
						String deviceId = jsonObject.getString("data");
						// 获取deviceId之后 上传所有按键
						uploadKeys(deviceId);
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), "保存失败：" + errorMsg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void uploadKeys(String deviceId) {
		// 上传空调按键
		String buttonCmdS = "";
		String positionS = "";
		String nameS = "";
		// 遍历所有按键 如果按键是模式、风量 温度+和温度- 则跳过
		Key modeKey = new Key();
		Key windKey = new Key();
		Key tempKey = new Key();
		Log.e("wmy", "280 upload keys.size() = " + keys.size());
		for (int i = 0; i < keys.size(); i++) {
			if (keys.get(i).getKeyNum() != 811 && keys.get(i).getKeyNum() != 812 && keys.get(i).getKeyNum() != 832
					&& keys.get(i).getKeyNum() != 833) {
				buttonCmdS += keys.get(i).getCodeValue() + ",";
				positionS += keys.get(i).getKeyNum() + ",";
				nameS += KeyManager.getInstance().getKeyNameById((int) keys.get(i).getKeyNum()) + ",";
			}
			if (keys.get(i).getKeyNum() == 811 || keys.get(i).getKeyNum() == 812) {
				tempKey = keys.get(i);
			}
			if (keys.get(i).getKeyNum() == 832) {
				modeKey = keys.get(i);
			}
			if (keys.get(i).getKeyNum() == 833) {
				windKey = keys.get(i);
			}
		}
		Log.e("wmy", "init tempkey" + tempKey.getCmds().size());
		for (int i = 0; i < tempKey.getCmds().size(); i++) {
			buttonCmdS += tempKey.getCmds().get(i).getCmd()+",";
			if(tempKey.getCmds().get(i).getNum()==16){
				positionS += "10016,";
				nameS += "16度,";
			}else if(tempKey.getCmds().get(i).getNum()==17){
				positionS += "10017,";
				nameS += "17度,";
			}else if(tempKey.getCmds().get(i).getNum()==18){
				positionS += "10018,";
				nameS += "18度,";
			}else if(tempKey.getCmds().get(i).getNum()==19){
				positionS += "10019,";
				nameS += "19度,";
			}else if(tempKey.getCmds().get(i).getNum()==20){
				positionS += "10020,";
				nameS += "20度,";
			}else if(tempKey.getCmds().get(i).getNum()==21){
				positionS += "10021,";
				nameS += "21度,";
			}else if(tempKey.getCmds().get(i).getNum()==22){
				positionS += "10022,";
				nameS += "22度,";
			}else if(tempKey.getCmds().get(i).getNum()==23){
				positionS += "10023,";
				nameS += "23度,";
			}else if(tempKey.getCmds().get(i).getNum()==24){
				positionS += "10024,";
				nameS += "24度,";
			}else if(tempKey.getCmds().get(i).getNum()==25){
				positionS += "10025,";
				nameS += "25度,";
			}else if(tempKey.getCmds().get(i).getNum()==26){
				positionS += "10026,";
				nameS += "26度,";
			}else if(tempKey.getCmds().get(i).getNum()==27){
				positionS += "10027,";
				nameS += "27度,";
			}else if(tempKey.getCmds().get(i).getNum()==28){
				positionS += "10028,";
				nameS += "28度,";
			}else if(tempKey.getCmds().get(i).getNum()==29){
				positionS += "10029,";
				nameS += "29度,";
			}else if(tempKey.getCmds().get(i).getNum()==30){
				positionS += "10030,";
				nameS += "30度,";
			}else if(tempKey.getCmds().get(i).getNum()==31){
				positionS += "10031,";
				nameS += "31度,";
			}
			
		}
		Log.e("wmy", "init windKey = " + windKey.getCmds().size());
		for (int i = 0; i < windKey.getCmds().size(); i++) {
			// Log.i("wmy", i + " modeKey.getCmds().get(i).getNum() = " +
			// modeKey.getCmds().get(i).getNum());
			buttonCmdS += windKey.getCmds().get(i).getCmd()+",";
			Log.i("wmy", windKey.getCmds().get(i).getNum() + " " + windKey.getCmds().get(i).getCmd());
			if (windKey.getCmds().get(i).getNum() == 1) {
				positionS += "10101,";
				nameS += "一档,";
			} else if (windKey.getCmds().get(i).getNum() == 2) {
				positionS += "10102,";
				nameS += "二档,";
			} else if (windKey.getCmds().get(i).getNum() == 3) {
				positionS += "10103,";
				nameS += "三档,";
			} else if (windKey.getCmds().get(i).getNum() == 4) {
				positionS += "10104,";
				nameS += "四档,";
			} else if (windKey.getCmds().get(i).getNum() == 5) {
				positionS += "10105,";
				nameS += "自动,";
			}
		}
		Log.e("wmy", "init modeKey = " + modeKey.getCmds().size());
		for (int i = 0; i < modeKey.getCmds().size(); i++) {
			buttonCmdS += modeKey.getCmds().get(i).getCmd()+",";
			Log.i("wmy", modeKey.getCmds().get(i).getNum() + " " + modeKey.getCmds().get(i).getCmd());
			if(modeKey.getCmds().get(i).getNum() ==1){
				positionS += "10201,";
				nameS += "送风,";
			}else if(modeKey.getCmds().get(i).getNum()==2){
				positionS += "10202,";
				nameS += "制冷,";
			}else if(modeKey.getCmds().get(i).getNum()==3){
				positionS += "10203,";
				nameS += "制暖,";
			}else if(modeKey.getCmds().get(i).getNum()==4){
				positionS += "10204,";
				nameS += "抽湿,";
			}else if(modeKey.getCmds().get(i).getNum()==5){
				positionS += "10205,";
				nameS += "自动,";
			}
			
		}

		if (buttonCmdS.length() > 1) {
			buttonCmdS = buttonCmdS.substring(0, buttonCmdS.length() - 1);
		}
		if (positionS.length() > 1) {
			positionS = positionS.substring(0, positionS.length() - 1);
		}
		if (nameS.length() > 1) {
			nameS = nameS.substring(0, nameS.length() - 1);
		}
		Log.e("wmy", "");
		RequestParams params = new RequestParams(HttpURL.UPLOAD_REMOTE_KEY_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("buttonCmdS", buttonCmdS);
			obj.put("key", "10000");
			obj.put("positionS", positionS);
			obj.put("deviceId", deviceId);
			obj.put("nameS", nameS);
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.e("wmy", " upload key = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("wmy", "upload key result=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String value = jsonObject.getString("resultCode");
					if (value.equals("1")) {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						ToastShow.Show(getApplicationContext(), "保存成功");
						KeyManager.getInstance().clear();
						DIYAirRemoteActivity.diyAirRemoteActivity.finish();
						RemoteSelectionActivity.remoteSelectionActivity.finish();
						DIYActivity.diyActivity.finish();
						DIYActivity1.diyActivity1.finish();
						finish();
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), "保存失败：" + errorMsg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

}
